<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *报价单
 */
class Quote extends Model
{
    use SoftDelete;

    protected $name = 'qingdongams_quote';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
// 追加属性
    protected $append = [
        'show_staff_data',
    ];

    public static function createQuote($params)
    {
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                $other[$name] = $val;
                unset($params[$name]);
            }
        }
        $is_check = $params['is_check'] ?? 0;
        unset($params['is_check']);
        if ($is_check == 1) {
            $params['check_status'] = 0;
            $params['next_staff_id'] = explode(',', $params['flow_staff_ids'])[0];//第一位即下一位审核人
        } else {
            $params['check_status'] = 2;
        }

        $product = [];
        if ($params['product']) {
            $product = $params['product'];
            unset($params['product']);
        }

        $params['product_type'] = json_encode($params['product_type'] ?? []);
        $params['clause'] = htmlentities($params['clause'] ?? '');
        $staff = Staff::info();
        if (!empty($staff)) {
            $params['create_staff_id'] = $staff->id;
            $params['owner_staff_id'] = $staff->id;
        }
        if ($is_check == 1) {
            $flow = Flow::getsteplist(Flow::CONTRACT_STATUS);
            $params['flow_id'] = $flow['flow_id'];
            $params['order_id'] = $flow['order_id'];

            if ($flow['status'] == 0) {//发起人自选
                if (empty($params['flow_staff_ids'])) {
                    throw new Exception('审批人必须选择');
                }
                $params['flow_staff_ids'] = trim($params['flow_staff_ids']);
            } else {
                $params['flow_staff_ids'] = trim($flow['flow_staff_ids']);
            }
        }

        $customer = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $customer->allowField(true)->save($params);
        $lastId = $customer->getLastInsID();
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($customer->getError());
        }
        $otherModel = new QuoteOther();
        if ($otherModel->save(['id' => $lastId, 'other' => json_encode($other, JSON_UNESCAPED_UNICODE)]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }
        $addProduct = [];
        foreach ($product as $v) {
            $addProduct[] = [
                'quote_id' => $lastId,
                'config' => json_encode($v['config'] ?? []),
                'config_desc' => $v['config_desc'] ?? '',
                'number' => $v['number'] ?? '',
                'price' => $v['price'] ?? '',
                'product_id' => $v['product_id'] ?? '',
                'remarks' => $v['remarks'] ?? '',
            ];
        }
        if ($addProduct) {
            $productModel = new QuoteProduct();
            $productModel->allowField(true)->insertAll($addProduct);
        }

        if (isset($params['flow_staff_ids']) && $params['flow_staff_ids'] && $is_check == 1) {
            $staff_id = explode(',', $params['flow_staff_ids'])[0];

            ExamineRecord::addExaminse(ExamineRecord::QUOTE_TYPE, $lastId, $staff_id);
        }

        StaffSignIn::quickSignIn($params['customer_id'],
            "新增报价单:单号:".$params['number'],
            ['relation_process'=>'备注']);
        OperationLog::createLog(OperationLog::QUOTE_TYPE, $lastId, '创建报价单');


        return $lastId;
    }

    //创建人

    /**
     *修改报价单
     */
    public static function updateQuote($params)
    {
        //自定义字段
        $other = [];
        foreach ($params as $name => $val) {
            if (strstr($name, 'other_') !== false) {
                $other[$name] = $val;
                unset($params[$name]);
            }
        }
        $product = [];
        if ($params['product']) {
            $product = $params['product'];
            unset($params['product']);
        }
        $is_check = $params['is_check'] ?? 0;
        unset($params['is_check']);
        if ($is_check == 1 && isset($params['flow_staff_ids'])) {
            $params['check_status'] = 0;
            $params['next_staff_id'] = explode(',', $params['flow_staff_ids'])[0];//第一位即下一位审核人
        } else {
            $params['check_status'] = 2;
        }

        $params['product_type'] = json_encode($params['product_type'] ?? []);
        $params['clause'] = htmlentities($params['clause'] ?? '');
        $customer = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $customer->isUpdate(true)->allowField(true)->save($params, ['id' => $params['id']]);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($customer->getError());
        }
        $otherModel = new QuoteOther();
        if ($otherModel->save(['other' => json_encode($other, JSON_UNESCAPED_UNICODE)], ['id' => $params['id']]) === false) {
            // 验证失败 输出错误信息
            throw new Exception($otherModel->getError());
        }
        $addProduct = [];
        foreach ($product as $v) {
            if(isset($v['id']))unset($v['id']);
            $v['quote_id'] = $params['id'];
            $v['config'] = json_encode($v['config'] ?? []);
            $addProduct[] = $v;
        }
        $productModel = new QuoteProduct();
        $productModel->where(['quote_id' => $params['id']])->delete();
        if ($addProduct) {
            $productModel->allowField(true)->saveAll($addProduct);
        }
        //撤回审批
        ExamineRecord::cancelExaminse(ExamineRecord::QUOTE_TYPE, $params['id']);
        if (isset($params['flow_staff_ids']) && $params['flow_staff_ids'] && $is_check == 1) {
            $staff_id = explode(',', $params['flow_staff_ids'])[0];

            ExamineRecord::addExaminse(ExamineRecord::QUOTE_TYPE, $params['id'], $staff_id);
        }
       $edit_reason= $params['edit_reason'] ?? '';
        OperationLog::createLog(OperationLog::QUOTE_TYPE, $params['id'], '修改报价单<br>备注：' . $edit_reason);
        return true;
    }

    //负责人

    public static function transferQuote($id, $staff_id, $desc = '')
    {
        $show_staff_id = JointFollow::transfer(JointFollow::QUOTE_TYPE, $id, $staff_id);
        $result = self::where(['id' => $id])->update(['owner_staff_id' => $staff_id, 'show_staff_id' => $show_staff_id]);
        if (empty($result)) {
            throw new Exception('修改负责人失败，请重新尝试');
        }
        $row = self::where(['id' => $id])->with(['customer', 'ownerStaff'])->find();

        $newStaff = Staff::get($staff_id);
        $staff = Staff::info();
        $log = $staff->name . " 将报价单【{$row['customer']['name']}】" . '由原负责人:' . $row['owner_staff']['name'] . '变更为: ' . $newStaff['name'] . ';原因：' . $desc;
        OperationLog::createCustomerLog($id, $log);
        Message::addMessage(Message::CUSTOMER_TYPE, $id, $staff_id, $staff->id, $log, 4);
        Message::addMessage(Message::CUSTOMER_TYPE, $id, $row['owner_staff_id'], $staff->id, $log, 4);

        return true;
    }

    public function getShowStaffDataAttr($value, $data)
    {
        if (!isset($data['show_staff_id'])) {
            return '';
        }
        $ids = explode(',', $data['show_staff_id']);
        return Staff::where(['id' => ['in', $ids]])->field('id,name,img,post,mobile')->select();
    }

    public function getCreatetimeAttr($value)
    {
        if ($value) {
            return date('Y-m-d H:i', $value);
        }

        return $value;
    }
    public function getUpdatetimeAttr($value)
    {
        if ($value) {
            return date('Y-m-d H:i', $value);
        }

        return $value;
    }

    //客户

    public function createStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
    }


    //联系人

    public function ownerStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'owner_staff_id')->field('id,name,img');
    }

    //创建报价单

    public function orderStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'order_staff_id')->field('id,name,img,mobile');
    }

    public function customer()
    {
        return $this->hasOne(Customer::class, 'id', 'customer_id')->field('id,name,follow,address');
    }

    //获取联系人信息
    public function contacts()
    {
        return $this->hasOne(Contacts::class, 'id', 'contacts_id')->field('id,name,mobile,telephone,mobilecode,region');
    }

    public function product()
    {
        return $this->hasMany(QuoteProduct::class, 'quote_id', 'id')->with('product');
    }

}
